#include<stdio.h>

#include<alsa/global.h>
#include<alsa/asoundlib.h>

int set_playback_volume(long volume)
{
	snd_mixer_t *handle = NULL;
	snd_mixer_selem_id_t *sid = NULL;
	snd_mixer_elem_t *elem = NULL;
	snd_mixer_selem_channel_id_t channelId = SND_MIXER_SCHN_REAR_LEFT;

	int ret = 0;
	ret = snd_mixer_open(&handle, 0);
	if (ret < 0) {
		printf("snd_mixer_open error!\n");
		goto error;
	}
	
	const char *card = "default";
	ret = snd_mixer_attach(handle, card);
	if (ret < 0) {
		printf("snd_mixer_attach error!\n");
		goto error;
	}

	const char *selem_name = "Playback";
	snd_mixer_selem_register(handle, NULL, NULL);
	snd_mixer_load(handle);
	snd_mixer_selem_id_alloca(&sid);
	snd_mixer_selem_id_set_index(sid, 0);
	snd_mixer_selem_id_set_name(sid, selem_name);
	elem = snd_mixer_find_selem(handle, sid);
	if (NULL == elem) {
		printf("snd_mixer_find_selem\n");
		goto error;
	}

	long def_vol = 0;
	ret = snd_mixer_selem_get_playback_volume(elem, channelId, &def_vol);
	if (ret < 0) {
		printf("get playback play_volume failed\n");
		goto error;
	}
	printf("default play_volume = %lu\n", def_vol);

	long min = 0, max = 0;
	ret = snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
	if (ret < 0) {
		printf("get range failed\n");
		goto error;
	}

	ret = snd_mixer_selem_set_playback_volume_all(elem, volume * (max - min) / 100);
	if (ret < 0) {
		printf("set playback play_volume failed\n");
		goto error;
	}

	ret = snd_mixer_selem_get_playback_volume(elem, channelId, &def_vol);
	if (ret < 0) {
		printf("get playback play_volume failed\n");
		goto error;
	}

	printf("set play volume = %lu\n", def_vol);
	ret = 0;

error:
	if (NULL != handle) {
		snd_mixer_close(handle);
		handle = NULL;
	}
	return ret;
}
